package org.suspi.skarabee.monitoring;
import java.text.DecimalFormat;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.merge.skarabee.R;

/**
 * A simple {@link android.support.v4.app.Fragment} subclass. Activities that
 * contain this fragment must implement the
 * {@link PortInfoFragment.OnFragmentInteractionListener} interface to handle
 * interaction events. Use the {@link PortInfoFragment#newInstance} factory
 * method to create an instance of this fragment.
 * 
 */
public class PortInfoFragment extends Fragment {

	//private View v;
	private MHandler handler;
	private TextView currentValueTV;
	private TextView voltageValueTV;



	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		LayoutInflater lf = getActivity().getLayoutInflater();   
		View view =  lf.inflate(R.layout.fragment_port_info, container, false);
		currentValueTV = (TextView)view.findViewById(R.id.ampTV);
		voltageValueTV = (TextView)view.findViewById(R.id.voltTV);
		handler = new MHandler();
		return view;

	}

	@Override
	public void onPause() {
		super.onPause();
	}

	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
	}

	public void setVoltage(String voltage){
		voltageValueTV.setText(voltage);
	}

	public void setCurrent(String current){
		currentValueTV.setText(current);
	}

	public void setData(Bundle bundle){
		notifyMessage(bundle);
	}

	private String roundTwoDecimals(String s) {
		double d = Double.parseDouble(s);
		DecimalFormat twoDForm = new DecimalFormat("#.##");
		return Double.valueOf(twoDForm.format(d)).toString();
	}
	private class MHandler extends Handler {
		@Override
		public void handleMessage(Message msg) {
			Bundle bundle = msg.getData();
			if(bundle.containsKey("voltage")) {
				String value = roundTwoDecimals(bundle.getString("voltage"));
				voltageValueTV.setText(value + " V");
			}
			if(bundle.containsKey("ampere")){
				String value = roundTwoDecimals(bundle.getString("ampere"));
				currentValueTV.setText(value + " A");
			}
		}
	}

	private void notifyMessage(Bundle b){
		Message msg = handler.obtainMessage();
		msg.setData(b);
		handler.sendMessage(msg);
	}


}
